package com.facebook.utils 
{
	import com.facebook.commands.FacebookCall;
	import com.facebook.data.FacebookData;
	import com.facebook.errors.FacebookError;
	import com.facebook.utils.connectionUtils.abstract.aConnectUtil;

	import flash.display.LoaderInfo;
	import flash.external.ExternalInterface;

	/**
	 * @author Ben Smith
	 * Thank you to ADOBE for their original creation of this class;
	 */
	public class FacebookConnectUtils extends aConnectUtil 
	{
  
                protected static var externalInterfaceCallId:Number = 0;
                protected static var externalInterfaceCalls:Object = {};
                protected static var hasCallback:Boolean = false;
                
                protected var _loaderInfo:LoaderInfo;
                
         
                static private var _flashName:String="flashcontent";
                
                public function FacebookConnectUtils(loaderInfo:LoaderInfo) {
                      
                        
                        if (hasCallback == false) {
                                ExternalInterface.addCallback('handleConnectCallback', handleConnectCallback);
                                hasCallback = true;
                        }
                        
                        _loaderInfo = loaderInfo;
                        _flashName=loaderInfo.parameters['as_swf_name'];
						
                }
               
                
                
                
                static public function createAnonymousCallFunction():String{
                	return 'function(response,exception,externalInterfaceCallId){document.'+_flashName+'.handleConnectCallback(response,exception,'+externalInterfaceCallId+')})'
                }
                
            	static public function registerCall(fbCall:FacebookCall):void {
                        externalInterfaceCalls[externalInterfaceCallId] = fbCall;
                        ++externalInterfaceCallId;
                }
                
               
                
                protected static function handleConnectCallback(result:Object, exception:Object, externalInterfaceCallId:String):void {
                   
                        var call:FacebookCall = externalInterfaceCalls[externalInterfaceCallId];
                        if (result) {
                                var fbData:FacebookData = new FacebookData();
                                fbData.result = result as Object
                                call.handleResult(fbData);
                        } else {
                                var error:FacebookError = new FacebookError();
                                error.result = exception as String;
                                call.handleError(error);
                        }
                        
                        delete externalInterfaceCalls[externalInterfaceCallId];
                }
                
        }
}
